<template>
  <el-card class="box-card">
    <el-button type="primary" icon="Plus" @click="addTrademark">添加品牌</el-button>
    <!-- 表格 -->
    <el-table style="margin: 10px 0px;" border stripe :data="trademarkShow">
      <!-- 列 -->
      <el-table-column label="序号" width="80px" align="center" type="index"></el-table-column>
      <!--table-column:默认展示数据使用div,不推荐  -->
      <!-- 使用solt插槽 -->
      <el-table-column label="品牌名称" align="center">
        <template #="{ row, $index }">
          <pre style="color:cornflowerblue">{{ row.tmName }}</pre>
        </template>
      </el-table-column>
      <el-table-column label="品牌LOGO" align="center">
        <template #="{ row, $index }">
          <img :src="row.logoUrl" style="width: 100px;height: 100px;">
        </template>
      </el-table-column>
      <el-table-column label="品牌操作" align="center">
        <template #="{ row, $index }">
          <el-button type="primary" size="small" icon="Edit" @click="updateTrademark(row)">修改</el-button>
          <el-popconfirm :title="`确定要删除${row.tmName}?`" width="200px" icon="Delete" @confirm="removeTrademark(row.id)">
            <template #reference>
              <el-button type="danger" size="small" icon="Delete">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[3, 5, 9]"
      :background=true layout=" prev, pager, next, jumper, ->, sizes, total" :total="total"
      @size-change="handleSizeChange" @current-change="getTrademark" />
  </el-card>
  <!-- dialog组件：用在添加品牌与修改品牌 -->
  <el-dialog v-model="dialogFormVisible" :title="trademarkParams.id ? '修改品牌' : '添加品牌'">
    <!-- model：表单校验对象 -->
    <el-form style="width: 80%" :model="trademarkParams" :rules="rules" ref="formRef">
      <!-- form-item的prop属性:需要进行校验的字段名 -->
      <el-form-item label="品牌名称" label-width="90px" prop="tmName">
        <el-input placeholder="请输入品牌名称" v-model="trademarkParams.tmName"></el-input>
      </el-form-item>
      <el-form-item label="品牌logo" label-width="90px" prop="logoUrl">
        <!-- upload属性：action->用于请求url -->
        <!-- before-upload:约束文件大小与内容 -->
        <el-upload class="avatar-uploader" action="/api/admin/product/fileUpload" :trademarkShow-file-list="false"
          :before-upload="beforeAvatarUpload" :on-success="handleAvatarSuccess">
          <img v-if="trademarkParams.logoUrl" :src="trademarkParams.logoUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" size="default" @click="cancel">取消</el-button>
      <el-button type="primary" size="default" @click="confirm">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, nextTick } from 'vue'
//引入接口
import { reqTrademark, reqAddOrUpdateTrademark, reqDeleteTrademark } from '@/api/product/trademark';
import type UploadProps from 'element-plus'
import { ElMessage } from 'element-plus'
//全部品牌数据的ts类型
import { Records, TradeMarkResponseData, TradeMark } from '@/api/product/trademark/types';
//当前页
let currentPage = ref<number>(1)
//每页显示多少数据
let pageSize = ref<number>(3)
//总数
let total = ref<number>(0)
//当前页码展示数据
let trademarkShow = ref<Records>([])
//对话框是否显示
let dialogFormVisible = ref<boolean>(false)
//定义表单收集新增品牌数据
let trademarkParams = reactive<TradeMark>({
  tmName: '',
  logoUrl: ''
})
//form组件实例
let formRef = ref()

onMounted(() => {
  getTrademark()
})

//自定义校验方法
const validatorTmName = (rule: any, value: any, callBack: any) => {
  if (value.trim().length >= 2) {
    callBack()//放行函数
  } else {
    callBack(new Error("品牌名称需大于两位！"))
  }
}
const validatorLogoUrl = (rule: any, value: any, callBack: any) => {
  console.log(value)
  //这里的value:图片的地址
  if (value) {
    callBack()
  } else {
    callBack(new Error("请上传品牌logo图片！"))
  }

}
//表单校验规则
const rules = {
  // blur:失去焦点触发
  tmName: [{ required: true, trigger: 'blur', validator: validatorTmName }],
  logoUrl: [{ required: true, trigger: 'blur', validator: validatorLogoUrl }]
}


//获取当前页码数据
//调用该方法时，如果没有传递参数就默认为1
const getTrademark = async (number = 1) => {
  currentPage.value = number
  let result: TradeMarkResponseData = await reqTrademark(currentPage.value, pageSize.value)
  if (result.code == 200) {
    total.value = result.data.total
    trademarkShow.value = result.data.records
  }
}

//添加品牌按钮的回调
const addTrademark = () => {
  //显示对话框
  dialogFormVisible.value = true
  //清空表单收集数据
  trademarkParams.tmName = ''
  trademarkParams.logoUrl = ''
  trademarkParams.id = 0

  //清除校验留下的信息
  //第一次点击时，没有formRef组件实例,调用时会报错，所以这里加上？
  // formRef.value?.clearValidate('tmName')
  // formRef.value?.clearValidate('logoUrl')

  //使用nexttick解决上面问题
  //响应式数据发生变化之后，获取到更新后的form组件实例
  nextTick(() => {
    formRef.value.clearValidate('tmName')
    formRef.value.clearValidate('logoUrl')
  })
}

//修改品牌按钮的回调
const updateTrademark = (row: TradeMark) => {
  // 清除校验留下的信息
  nextTick(() => {
    formRef.value.clearValidate('tmName')
    formRef.value.clearValidate('logoUrl')
  })
  //显示对话框
  dialogFormVisible.value = true

  // //显示对话框的数据
  // trademarkParams.tmName = row.tmName
  // trademarkParams.logoUrl = row.logoUrl
  // //修改请求时需要带id
  // trademarkParams.id = row.id

  //es6语法  合并对象
  Object.assign(trademarkParams, row)//相当于上面三行代码
}

//删除品牌气泡框确认的回调
const removeTrademark = async (id: number) => {
  let result = await reqDeleteTrademark(id);
  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: "删除品牌成功！"
    })
    //刷新
    getTrademark(trademarkShow.value.length >= 1 ? currentPage.value : currentPage.value - 1)
  } else {
    ElMessage({
      type: 'error',
      message: "删除品牌失败！"
    })
  }
}
//对话框确认按钮回调
const confirm = async () => {
  //发请求前，对整个表单进行校验，校验成功才发请求
  //validate方法：返回一个promise对象
  await formRef.value.validate()
  //await失败后不会执行后面的代码

  let result: any = await reqAddOrUpdateTrademark(trademarkParams)
  if (result.code == 200) {
    //关闭对话框
    dialogFormVisible.value = false
    ElMessage({
      type: 'success',
      message: trademarkParams.id ? '修改品牌成功！' : '添加品牌成功！'
    })
    //刷新列表
    getTrademark(trademarkParams.id ? currentPage.value : 1)
  } else {
    dialogFormVisible.value = false
    ElMessage({
      type: 'error',
      message: trademarkParams.id ? '修改品牌失败！' : '添加品牌失败！'
    })
  }
}

//对话框取消按钮回调
const cancel = () => {
  dialogFormVisible.value = false
}

//下拉菜单页码发生变化时触发
//对于自定义事件，组件pagination回传了数据(当前选中的下拉菜页码)
const handleSizeChange = (pageSize) => {
  console.log(pageSize)
  //再次获取当前页码数据
  //这里需要注意一下，当下拉菜单页码发生变化时，让其为1
  // currentPage.value = 1
  getTrademark()
}

//分页器当前页码发生改变时触发
//对于自定义事件，组件pagination回传了数据(当前的选中的页码)
// const handleCurrentChange = (a) => {
//   console.log(a)
//   //再次获取当前页码数据
//   getTrademark()
// }

//文件上传前触发的钩子
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  //这里要求上传文件格式：jpg,png,gif  大小<4m
  if (rawFile.type == 'image/png' || rawFile.type == 'image/jpeg' || rawFile.type == 'image/gif') {
    if (rawFile.size / 1024 / 1024 < 4) {
      return true
    } else {
      ElMessage({
        type: 'error',
        message: '文件需小于4M!'
      })
      return false
    }
  } else {
    ElMessage({
      type: 'error',
      message: '文件格式必须是png或jpeg或gif'
    })
    return false;
  }
}

//文件上传成功触发的钩子
const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
  // console.log("response:",response) 
  // console.log("uploadFile:",uploadFile)
  //收集上传图片地址，添加新的品牌时给服务器
  trademarkParams.logoUrl = response.data
  //图片上传成功，清除校验留下的信息
  formRef.value.clearValidate('logoUrl')

}
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>